
import 'package:flutter/material.dart';
import 'package:juju/conf/IMConf.dart';
import 'package:juju/fake/fake_message_tool.dart';
import 'package:juju/model/EventQueueModel.dart';

class NewFriendsPage extends StatefulWidget {
  const NewFriendsPage({Key? key}) : super(key: key);

  @override
  State<NewFriendsPage> createState() => _NewFriendsPageState();
}

class _NewFriendsPageState extends State<NewFriendsPage> {
  @override
  Widget build(BuildContext context) {
    List<ContactNotifyEvent> evno =
        EventQueueModel.getInstance().jmContactNotifyEvents;
    for (var ev in evno) {
      print(
          "=================================\n${ev.fromUserName}\n${ev.reason}\n${ev.type}\n============================");
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text("新的朋友"),
      ),
      body: Container(
        color: Colors.grey[50],
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: EventQueueModel.getInstance().jmContactNotifyEvents.length,
        ),
      ),
    );
  }

  Widget _itemBuilder(BuildContext buildContext, int position) {
    return Container(
      padding: const EdgeInsets.only(
        top: 5.0,
        bottom: 5.0,
      ),
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: ListTile(
        title: Text(EventQueueModel.getInstance()
            .jmContactNotifyEvents[position]
            .fromUserName),
        subtitle: Text(EventQueueModel.getInstance()
            .jmContactNotifyEvents[position]
            .reason),
        trailing: FloatingActionButton(
          onPressed: () {
            _acceptInvitation(
                EventQueueModel.getInstance()
                    .jmContactNotifyEvents[position]
                    .fromUserName,
                position: position);
          },
          child: const Text("同意"),
        ),
      ),
    );
  }

  void _acceptInvitation(String username, {int? position}) async {
    await IMConf.getInstance()
        .getJmessage()
        .acceptInvitation(username: username)
        .then(
      (value) {
        print("========================== 成功添加 =========================");
        EventQueueModel.getInstance().jmContactNotifyEvents.removeAt(position!);
        setState(() {});
      },
      onError: (e) {
        print("========================== 添加失败 =========================");
        print("|\n|\n----- ${e.toString()}");
      },
    );
  }
}
